package com.xlf.common.auth.dao;

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author xlf
 */
@Data
//对象中如果有setXXX或getXXX方法，或返回值为Boolean或boolean的isXXX方法，但没有对应的XXX字段，使用Jackson2JsonRedisSerializer序列化后json中会有对应的key值XXX，从而会导致反序列化失败。
@JsonIgnoreProperties(ignoreUnknown = true)
public abstract class JwtUserDetails implements UserDetails {

    //存活日期
    private Long expireTime;

    //上次更新令牌时间
    private Long loginTime;

    /**
     * 用户唯一标识。做为key将此类存入redis
     */
    private String uuid;

    /**
     * 用户id
     */
    private Object userId;


    /**
     * 登录IP地址
     */
    private String ipaddr;

    /**
     * 登录地点
     */
    private String loginLocation;

    /**
     * 浏览器类型
     */
    private String browser;

    /**
     * 操作系统
     */
    private String os;



    /**
     * 用户的权限
     */
    Set<String> permissions;




    /**
     * JsonIgnore：这个SimpleGrantedAuthority没有默认的无参构造方法会导致反序列化失败
     */
    @JsonIgnore
    List<SimpleGrantedAuthority> authorities;

    public abstract Object getUserId();

    public JwtUserDetails(Set<String>collectors){
        this.permissions  = collectors;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        if (authorities!=null){
            return authorities;
        }
        if(permissions!=null)
            authorities = permissions.stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList());
        return authorities;
    }



}
